<?php
/**
 * Created by PhpStorm.
 * User: 84071
 * Date: 2018-03-29
 * Time: 15:11
 */
namespace app\common\controller;

use think\Controller;
use think\Image;

class Upload extends Controller{
    public $UpDir;
    public $LinshiDir;
    public function _initialize(){
        if(webCacheHas('webdb')){
            $webdb = webCacheGet('webdb');
        }else{
            $webdb = webdb();
        }
        $this->UpDir = $webdb['updir'].'/';
        $this->LinshiDir = $this->UpDir.'linshi/'.session('userdb.uid').'/';
        if (!file_exists($this->UpDir)) {
            @mkdir($this->UpDir);
        }
        if (!file_exists($this->LinshiDir)) {
            @mkdir($this->LinshiDir);
        }
    }
    //  上传文件
    public function upload($data){
        $saveName = $this->newname($data);
        $info = $data->move(ROOT_PATH . $this->LinshiDir, $saveName);
        if($info){
            $imgs = ([
                'title' => $info->getInfo('name'),
                'size' => $info->getInfo('size'),
                'name' => $this->LinshiDir.$info->getSaveName()
            ]);
            return $imgs;
        }
        return false;
    }
    //  处理文章中的图片
    public function articleimg($data,$imgurl,$geturl = true){
        $imgps = "/<[img|IMG].*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/";
        preg_match_all($pattern = $imgps, $data['oldimg'], $oldimg);//获得老的图片
        preg_match_all($pattern = $imgps, $data['newimg'], $newimg);//获得新的图片
        $oldimg = $oldimg[1];
        $newimg = $newimg[1];
        $newimg = array_flip($newimg);
        $newimg = array_flip($newimg);
        if(!empty($oldimg)){
            foreach ($oldimg as $v){
                $oldimgname[] = basename($v);
            }
        }
        //  处理新图片
        if(!empty($newimg)){
            foreach ($newimg as $k => $v){
                if(!empty($oldimgname)){
                    if(in_array(basename($v),$oldimgname)){
                        unset($newimg[$k]);
                    }
                }
                $newimgname[] = basename($v);
            }
        }
        //  处理老图片
        if(!empty($oldimg)){
            foreach ($oldimg as $k => $v){
                if(!empty($newimgname)){
                    if(in_array(basename($v),$newimgname)){
                        unset($oldimg[$k]);
                    }
                }
            }
        }
        //  开始移动
        if(!empty($newimg)){
            if(!file_exists($this->UpDir.$imgurl)){
                @mkdir($this->UpDir.$imgurl);
            }
            if($geturl == true){
                foreach ($newimg as $k => $v){
                    if(preg_match('/http:\/\/*\??[\w=&\+\%]*/is',$v) || preg_match('/https:\/\/*\??[\w=&\+\%]*/is',$v)){
                        $newname = $this->range($v,$imgurl);
                    }elseif(preg_match('/^(data:\s*image\/(\w+);base64,)/',$v,$type)){
                        $newname = $this->base64($v,$type,$imgurl);
                    }elseif(preg_match("/{$this->UpDir}",$v)){
                        $newname = $this->fileMove($v,$imgurl);
                    }
                    if(isset($newname)){
                        $data['newimg'] = str_ireplace($v,'/'.$this->UpDir.$newname,$data['newimg']);
                    }
                }
            }else{
                foreach ($newimg as $k => $v){
                    if(preg_match("/{$this->UpDir}",$v)){
                        $newname = $this->fileMove($v,$imgurl);
                    }
                    if(isset($newname)){
                        $data['newimg'] = str_ireplace($v,'/'.$this->UpDir.$newname,$data['newimg']);
                    }
                }
            }
        }
        if(!empty($oldimg)){
            foreach ($oldimg as $v){
                @unlink(ROOT_PATH.$this->UpDir.'/'.$v);
            }
        }
        return $data['newimg'];
    }
    /**
     * @param $data 要处理的数据
     * @param $file_dir 目标地址
     * @param string $moves 处理方式：copy为复制，rename为移动
     * @param bool $dels 是否删除源文件
     * @return string 返回文件地址
     */
    public function fileMove($data,$file_dir,$moves = 'rename',$dels=true){
        if(is_array($data)){
            foreach ($data as $key => $val){
                $newdata[$key] = $this->fileMove($val,$file_dir,$moves,$dels);
            }
            return $newdata;
        }
        /*重命名*/
        $saveName = $this->newname($data);
        $fileFix = pathinfo($data, PATHINFO_EXTENSION);
        $fileName = $saveName.'.'.$fileFix;
        /*  检测文件夹是否存在 */
        if (!file_exists($this->UpDir.$file_dir)) {
            @mkdir($this->UpDir.$file_dir);
        }
        //       检查文件路径
        if(preg_match("/{$this->UpDir}",$data)){
            $data = str_ireplace("/{$this->UpDir}",$this->UpDir,$data);
        }
        /*移动文件*/
        if($moves == 'rename'){
            @rename($data,ROOT_PATH.$this->UpDir.$file_dir.'/'.$fileName);
        }else{
            @copy($data,ROOT_PATH.$this->UpDir.$file_dir.'/'.$fileName);
        }
        if($dels && $moves != 'rename'){
            @unlink(ROOT_PATH.$data);
        }
        return $file_dir.'/'.$fileName;
    }

    protected function newname($data){
        $imgmd5 = cxbsmd5($data.substr(md5(time()),0,8));
        $saveName = '';
        for ( $i = 0; $i < 10; $i++ ) {
            $saveName .= substr($imgmd5, mt_rand(0, strlen($imgmd5) - 1), 1);
        }
        return $saveName;
    }
    //  获取远程图片
    protected function range($img,$imgurl){
        $mimes = array(
            'image/bmp'=>'bmp',
            'image/gif'=>'gif',
            'image/jpg'=>'jpg',
            'image/jpeg'=>'jpeg',
            'image/png'=>'png',
            'image/x-icon'=>'ico'
        );
        if(($headers=get_headers($img, 1))!==false) {
            // 获取响应的类型
            $type = $headers['Content-Type'];
            // 如果符合类型
            if (isset($mimes[$type])) {
                $imgmimes = $mimes[$type];
                $newname = $this->newname($img);
                $newname = $imgurl.'/'.$newname.'.'.$imgmimes;
                // 获取数据并保存
                file_put_contents($this->UpDir.'/'.$newname, file_get_contents($img));
                return $newname;
            }
        }
        return $img;
    }
    public function base64($img,$type,$imgurl){
        $imgpng = $type[2];
        $newname = $this->newname($img);
        $newname = $imgurl.'/'.$newname.'.'.$imgpng;
        file_put_contents($this->UpDir.'/'.$newname, file_get_contents($img));
        return $newname;
    }
    //  处理缩略图
    public function pspicurl($img,$imgurl,$dels = true){
        if(preg_match('/http:\/\/*\??[\w=&\+\%]*/is',$img) || preg_match('/https:\/\/*\??[\w=&\+\%]*/is',$img)){
            $img = $this->UpDir.$this->range($img,$imgurl);
            $dels = true;
        }elseif(preg_match('/^(data:\s*image\/(\w+);base64,)/',$img,$type)){
            $img = $this->UpDir.$this->base64($img,$type,$imgurl);
            $dels = true;
        }
        $imgs = Image::open(ROOT_PATH.$img);
        $width = $imgs->width();
        $height = $imgs->height();
        $fileFix = pathinfo($img, PATHINFO_EXTENSION);
        $saveName =  $this->newname($img).'.'.$fileFix;
        if(!is_dir(ROOT_PATH.$this->UpDir.$imgurl)){
            @mkdir(ROOT_PATH.$this->UpDir.$imgurl);
        }
        $imgtu = array(
            '1' => array('w'=>'500','h'=>'500','q'=>'/1x1_'),
            '2' => array('w'=>'375','h'=>'375','q'=>'/4x3_'),
            '3' => array('w'=>'375','h'=>'375','q'=>'/3x4_'),
        );
        foreach ($imgtu as $k => $v){
            $this->thumbs($img,$v,$imgurl,$saveName);
        }
        $imgs->thumb($width,$height,Image::THUMB_FILLED)->save(ROOT_PATH.$this->UpDir.$imgurl.'/'.$saveName);
        $picurl = $imgurl.'/'.$saveName;
        unset($saveName);
        if($dels == true){
            @unlink($img);
        }
        return $picurl;
    }
//    生成缩略图
    public function thumbs($img,$data,$imgurl,$saveName){
        $imgs = Image::open(ROOT_PATH.$img);
        $imgs->thumb($data['w'], $data['h'],2)->save(ROOT_PATH.$this->UpDir.$imgurl.$data['q'].$saveName);
    }
    /**
     * @param $data 删除的文件内容
     * @return bool 返回结果
     */
    public function fileDel($data){
        if(is_array($data)){
            foreach ($data as $key => $val){
                $this->fileDel($val);
            }
            return true;
        }
        if(is_file(ROOT_PATH.$this->UpDir.$data)){
            @unlink(ROOT_PATH.$this->UpDir.$data);
        }
        return true;
    }
    //  隐藏真实地址，为防止更换网址出故障
    public function editadd($data,$adds = true,$weburl = null){
        if(is_array($data)){
            foreach ($data as $k => $v){
                $data[$k] = $this->editadd($v,$adds);
            }
        }
        if($adds == true){
            $data = str_replace("{$weburl}/{$this->UpDir}","http://www_cxbs_net/Ls_dir/",$data);
        }else{
            $data = str_replace("http://www_cxbs_net/Ls_dir/","{$weburl}/{$this->UpDir}",$data);
        }
        return $data;
    }
    //  生成推广图片文件
    public function tuiguang($uid,$shop,$erweima,$getdata){
        //  创建画布
        $image = imagecreatetruecolor($getdata['w'], $getdata['h']);
        //  生成二维码
        $imginfo = getimagesize(ROOT_PATH.$shop['picurl']);
        $erweima = $this->erweima($erweima);
        $sywjinfo = getimagesize($this->LinshiDir.$erweima);
        $sywj = imagecreatefrompng(ROOT_PATH.$this->LinshiDir.$erweima);
        if(!is_dir(ROOT_PATH.$this->UpDir.'tuiguang')){
            @mkdir(ROOT_PATH.$this->UpDir.'tuiguang');
        }
        //  产品缩略图宽度
        $wid = $getdata['w'] -10;
        //  标题位置
        $mwid = $getdata['h'] - $getdata['w'] - 120;
        // 价格位置
        $twid = $mwid / 2;

        if($imginfo['mime'] == 'image/bmp'){
            $picurl = imagecreatefromwbmp(ROOT_PATH.$shop['picurl']);
        }elseif($imginfo['mime'] == 'image/gif'){
            $picurl = imagecreatefromgif(ROOT_PATH.$shop['picurl']);
        }elseif($imginfo['mime'] == 'image/jpeg' || $imginfo['mime'] == 'image/jpg'){
            $picurl = imagecreatefromjpeg(ROOT_PATH.$shop['picurl']);
        }elseif($imginfo['mime'] == 'image/png'){
            $picurl = imagecreatefrompng(ROOT_PATH.$shop['picurl']);
        }
        //  定义颜色
        $bai = imagecolorallocate($image, 255, 255, 255);
        $hui = imagecolorallocate($image, 223, 223, 223);
        $hei = imagecolorallocate($image, 51, 51, 51);
        $qhui = imagecolorallocate($image, 102, 102, 102);
        $red = imagecolorallocate($image, 175, 0, 0);
        $fonts = ROOT_PATH.'public/fonts/msyh.ttf';
        //  写入产品图片
        imagefilledrectangle($image, 0, 0, $getdata['w'], $getdata['h'], $bai);
        imagecopyresampled($image, $picurl, 5, 5, 0, 0, $wid, $wid, $imginfo[0],$imginfo[0]);
        imageline($image, 3, 3, 3, $wid + 4, $hui); //插入l线
        imageline($image, 3, 3, $getdata['w'] - 3, 3, $hui); //插入T线
        imageline($image, $getdata['w'] - 3, 3, $getdata['w'] - 3, $wid + 4, $hui); //插入R线
        imageline($image, 3, $getdata['w'] - 3, $getdata['w'] - 3, $getdata['w'] - 3, $hui); //插入B线
        $temp = array("color" => array(0, 0, 0), "fontsize" =>14, "width" => $wid - 10, "left" => 3, "top" => $getdata['w'], "hang_size" => 32);
        $image = $this->draw_txt_to($image, $temp, $shop['title'], true);
        $temp = array("color" => array(175, 0, 0), "fontsize" =>18, "width" => $wid - 10, "left" => 3, "top" => $getdata['w'] + 60, "hang_size" => 40);
        $image = $this->draw_txt_to($image, $temp, $shop['money'], true);
        imageline($image, 5, $getdata['h'] - $mwid, $getdata['w'] - 5, $getdata['h'] - $mwid, $hui); //插入横线
        imagettftext($image, 12, 0, 5, $getdata['h'] - $twid - 10, $hei, $fonts, $shop['text']); //插入价格
        imagettftext($image, 12, 0, 5, $getdata['h'] - $twid + 20, $qhui, $fonts, $shop['webtitle']); //插入价格
        imagecopyresampled($image, $sywj, $getdata['w']- $mwid - 5, $getdata['h'] - $mwid + 2, 0, 0, $mwid, $mwid, $sywjinfo[0],$sywjinfo[0]);
        imagejpeg($image,ROOT_PATH.$this->UpDir.'tuiguang/'.$uid.'_'.$shop['aid'].'_tuiguang.jpg');
        @unlink($this->LinshiDir.$erweima);
        return $this->UpDir.'/tuiguang/'.$uid.'_tuiguang.jpg';
    }
    //  生成并保存二维码
    public function erweima($erweima){
        $mimes = array(
            'image/bmp'=>'bmp',
            'image/gif'=>'gif',
            'image/jpeg'=>'jpg',
            'image/png'=>'png',
            'image/x-icon'=>'ico'
        );
        if(($headers=get_headers($erweima, 1))!==false) {
            // 获取响应的类型
            $type = $headers['Content-Type'];
            // 如果符合类型
            if (isset($mimes[$type])) {
                $imgmimes = $mimes[$type];
                $newname = $this->newname($erweima).'.'.$imgmimes;
                // 获取数据并保存
                file_put_contents($this->LinshiDir.$newname, file_get_contents($erweima));
                return $newname;
            }
        }
    }
    /**
     * 文字自动换行算法
     * @param $card 画板
     * @param $pos 数组，top距离画板顶端的距离，fontsize文字的大小，width宽度，left距离左边的距离，hang_size行高
     * @param $str 要写的字符串
     * @param $iswrite  是否输出，ture，  花出文字，false只计算占用的高度
     * @return int 返回整个字符所占用的高度
     */
    function draw_txt_to($card, $pos, $str, $iswrite){
        $_str_h = $pos["top"];
        $fontsize = $pos["fontsize"];
        $width = $pos["width"];
        $margin_lift = $pos["left"];
        $hang_size = $pos["hang_size"];
        $temp_string = "";
        $font_file = ROOT_PATH.'public/fonts/msyh.ttf';
        $tp = 0;

        $font_color = imagecolorallocate($card, $pos["color"][0], $pos["color"][1], $pos["color"][2]);
        for ($i = 0; $i < mb_strlen($str); $i++) {
            $box = imagettfbbox($fontsize, 0, $font_file, $temp_string);
            $_string_length = $box[2] - $box[0];
            $temptext = mb_substr($str, $i, 1);
            $temp = imagettfbbox($fontsize, 0, $font_file, $temptext);
            if ($_string_length + $temp[2] - $temp[0] < $width) {//长度不够，字数不够，需要
                //继续拼接字符串。
                $temp_string .= mb_substr($str, $i, 1);
                if ($i == mb_strlen($str) - 1) {//是不是最后半行。不满一行的情况
                    $_str_h += $hang_size;//计算整个文字换行后的高度。
                    $tp++;//行数
                    if ($iswrite) {//是否需要写入，核心绘制函数
                        imagettftext($card, $fontsize, 0, $margin_lift, $_str_h, $font_color, $font_file, $temp_string);
                    }
                }
            } else {
//            打印输出，对字符串零时字符串置null
                $texts = mb_substr($str, $i, 1);//零时行的开头第一个字。
//            判断默认第一个字符是不是符号；
                $isfuhao = preg_match("/[\\pP]/u", $texts) ? true : false;//一行的开头这个字符，是不是标点符号
                if ($isfuhao) {//如果是标点符号，则添加在第一行的结尾
                    $temp_string .= $texts;
//                判断如果是连续两个字符出现，并且两个丢失必须放在句末尾的，单独处理
                    $f = mb_substr($str, $i + 1, 1);
                    $fh = preg_match("/[\\pP]/u", $f) ? true : false;
                    if ($fh) {
                        $temp_string .= $f;
                        $i++;
                    }
                } else {
                    $i--;
                }
                $tmp_str_len = mb_strlen($temp_string);
                $s = mb_substr($temp_string, $tmp_str_len-1, 1);//取零时字符串最后一位字符
                if ($this->is_firstfuhao($s)) {//判断零时字符串的最后一个字符是不是可以放在见面
                    //讲最后一个字符用“_”代替。指针前移动一位。重新取被替换的字符。
                    $temp_string=rtrim($temp_string,$s);
                    $i--;
                }
//            计算行高，和行数。
                $_str_h += $hang_size;
                $tp++;
                if ($iswrite) {
                    imagettftext($card, $fontsize, 0, $margin_lift, $_str_h, $font_color, $font_file, $temp_string);
                }
//           写完了改行，置null该行的临时字符串。
                $temp_string = "";
            }
        }
        return $card;
    }

    public  function is_firstfuhao($str){
        $fuhaos = array("\"", "“", "'", "<", "《",);
        return in_array($str, $fuhaos);
    }
}